package com.dnjn.happiness.common.config.handlers;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.dnjn.happiness.common.security.utils.SecurityUtils;
import com.dnjn.happiness.system.api.model.LoginUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;

import java.time.LocalDateTime;

@Slf4j
public class BaseMetaObjectHandler implements MetaObjectHandler {


    @Override
    public void insertFill(MetaObject metaObject) {
        // added at 240604 PM.
        setFieldValByName("tenantId", getLoginUser().getTenantId(), metaObject);

        setFieldValByName("createBy", getUserName(), metaObject);
        setFieldValByName("deleted", "0", metaObject);
        setFieldValByName("createTime", LocalDateTime.now(), metaObject);

        setFieldValByName("updateBy", getUserName(), metaObject);
        setFieldValByName("updateTime", LocalDateTime.now(), metaObject);
    }


    @Override
    public void updateFill(MetaObject metaObject) {
        setFieldValByName("updateBy", getUserName(), metaObject);
        setFieldValByName("updateTime", LocalDateTime.now(), metaObject);
    }

    protected LoginUser getLoginUser() {
        return SecurityUtils.getLoginUser();
    }

    protected String getUserName() {
        try {
            return getLoginUser().getUsername();
        } catch (Exception e) {
            log.warn(e.getMessage());
        }
        return "sys";
    }
}
